<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBookDetail, submitBorrowRequest, getSimilarBooks, addToFavorites, removeFromFavorites, checkIsFavorite, getBookRatings, averageBookRating } from '@/api/user'
import { Star, ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

interface BookDetail {
  bookId: number
  title: string
  author: string
  publishDate: number
  stockQuantity: number
  description: string
  coverImage: string
  popularityScore: number
  wordCount: number
  categoryName: string
}

const book = ref<BookDetail | null>(null)
const loading = ref(true)

// 修改评论相关数据结构
interface Comment {
  ratingId: number
  userId: number
  username: string
  rating: number
  comment: string
  createTime: string
  updateTime: string
}

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const comments = ref<Comment[]>([])

// 获取评论列表
const fetchComments = async () => {
  try {
    if (!book.value) return
    const res = await getBookRatings(book.value.bookId, currentPage.value, pageSize.value)
    if (res.data) {
      comments.value = res.data.results
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  }
}

// 页码改变时的处理函数
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchComments()
}

// 修改推荐图书的数据结构
interface RecommendedBook {
  bookId: number
  title: string
  author: string
  coverImage: string
  description: string
}

const recommendedBooks = ref<RecommendedBook[]>([])

// 添加获取相似图书的方法
const getSimilarRecommendations = async (bookId: number) => {
  try {
    const res = await getSimilarBooks(bookId)
    if (res.code === 0 && res.data) {
      recommendedBooks.value = res.data
    }
  } catch (error) {
    console.error('获取相似图书失败:', error)
  }
}

// 添加日期格式化方法
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleDateString()
}

// 添加收藏状态
const isFavorite = ref("0")

// 检查收藏状态
const checkFavoriteStatus = async (bookId: number) => {
  try {
    const res = await checkIsFavorite(bookId)
    if (res.code === 0) {
      isFavorite.value = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 处理收藏/取消收藏
const handleFavorite = async () => {
  if (!book.value) return

  try {
    if (isFavorite.value === "1") {
      // 添加确认对话框
      try {
        await ElMessageBox.confirm(
          '确定要取消收藏这本书吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        // 用户点击确定后执行取消收藏
        await removeFromFavorites(book.value.bookId)
        ElMessage.success('已取消收藏')
        isFavorite.value = "0"
      } catch (error) {
        // 用户点击取消按钮，不执行任何操作
        return
      }
    } else {
      await addToFavorites(book.value.bookId)
      ElMessage.success('收藏成功')
      isFavorite.value = "1"
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 添加平均评分数据
const averageRating = ref(0)

// 获取平均评分
const fetchAverageRating = async (bookId: number) => {
  try {
    const res = await averageBookRating(bookId)
    if (res.data) {
      averageRating.value = res.data
    }
  } catch (error) {
    console.error('获取平均评分失败:', error)
  }
}

// 获取图书详情
const getDetail = async () => {
  try {
    const bookId = route.query.id
    if (!bookId) {
      ElMessage.error('图书ID不能为空')
      return
    }

    const res = await getBookDetail(bookId as string)
    if (res.code === 0 && res.data) {
      book.value = res.data
      // 获取相似图书推荐
      await getSimilarRecommendations(res.data.bookId)
      // 检查收藏状态
      await checkFavoriteStatus(res.data.bookId)
      // 获取评论列表
      await fetchComments()
      // 获取平均评分
      await fetchAverageRating(res.data.bookId)
    }
  } catch (error) {
    ElMessage.error('获取图书详情失败')
  } finally {
    loading.value = false
  }
}

// 提交借阅申请
const handleBorrow = async () => {
  try {
    if (!book.value) return

    if (book.value.stockQuantity <= 0) {
      ElMessage.warning('当前图书无可借阅库存')
      return
    }

    const res = await submitBorrowRequest(book.value.bookId)
    if (res.code === 0) {
      ElMessage.success('借阅申请提交成功')
      // 更新库存数量
      book.value.stockQuantity--
    }
  } catch (error) {
    ElMessage.error('借阅申请提交失败')
  }
}

// 修改处理推荐图书点击的方法
const handleBookClick = async (book) => {
  // 更新路由参数
  await router.push({
    path: '/user/book-detail',
    query: { id: book.bookId }
  })
  // 手动重新获取数据
  await getDetail()
  // 滚动到页面顶部
  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // 使用平滑滚动
  })
}

// 修改路由参数变化的监听
watch(
    () => route.query.id,
    async (newId) => {
      if (newId) {
        loading.value = true
        await getDetail()
        // 滚动到页面顶部
        window.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
      }
    }
)

// 添加处理作者点击的方法
const handleAuthorClick = (author: string) => {
  router.push({
    path: '/user/author-books',
    query: { author }
  })
}

onMounted(() => {
  getDetail()
})
</script>

<template>
  <div class="book-detail-container">
    <!-- 顶部导航区 -->
    <div class="page-header">
      <el-button class="back-button" @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <!-- 主要内容区 -->
    <el-card v-loading="loading">
      <template v-if="book">
        <!-- 图书基本信息区 -->
        <div class="book-content">
          <div class="book-image">
            <img :src="book.coverImage" :alt="book.title">
            <div class="book-actions">
              <el-button
                  type="primary"
                  class="borrow-button"
                  @click="handleBorrow"
                  :disabled="book.stockQuantity <= 0"
              >
                {{ book.stockQuantity > 0 ? '申请借阅' : '暂无库存' }}
              </el-button>
              <el-button
                  :type="isFavorite === '1' ? 'danger' : 'warning'"
                  class="favorite-button"
                  @click="handleFavorite"
              >
                <el-icon><Star /></el-icon>
                {{ isFavorite === "1" ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>

          <div class="book-info">
            <h1 class="book-title">{{ book.title }}</h1>

            <el-descriptions :column="1" border>
              <el-descriptions-item label="作者">
                <span 
                  class="author-name clickable" 
                  @click.stop="handleAuthorClick(book.author)"
                >{{ book.author }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="分类">
                <el-tag size="small" type="info">{{ book.categoryName }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="出版日期">{{ formatDate(book.publishDate) }}</el-descriptions-item>
              <el-descriptions-item label="字数">{{ book.wordCount }}万字</el-descriptions-item>
              <el-descriptions-item label="热度">
                <div class="popularity-score">
                  <span class="score-number">{{ book.popularityScore }}</span>
                  <el-rate
                      v-model="book.popularityScore"
                      disabled
                      :show-score="false"
                  />
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="库存状态">
                <el-tag :type="book.stockQuantity > 0 ? 'success' : 'danger'">
                  {{ book.stockQuantity > 0 ? '可借阅' : '已借完' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="book-description">
              <h2>图书简介</h2>
              <p>{{ book.description }}</p>
            </div>
          </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section">
          <h2>读者评论</h2>
          <div class="rating-summary">
            <span class="average-rating-label">平均评分：</span>
            <el-rate
                v-model="averageRating"
                disabled
                show-score
                text-color="#ff9900"
                size="large"
            />
            <span class="rating-count">{{ total }}条评论</span>
          </div>

          <div class="comments-list">
            <el-empty v-if="!comments.length" description="暂无评论" />
            <template v-else>
              <div v-for="comment in comments" :key="comment.ratingId" class="comment-item">
                <div class="comment-header">
                  <div class="comment-info">
                    <span class="username">{{ comment.username }}</span>
                    <el-rate v-model="comment.rating" disabled />
                  </div>
                  <span class="comment-date">{{ comment.createTime }}</span>
                </div>
                <p class="comment-content">{{ comment.comment }}</p>
              </div>
              <!-- 分页器 -->
              <div class="pagination" v-if="total > pageSize">
                <el-pagination
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="total"
                    layout="prev, pager, next"
                    @current-change="handlePageChange"
                />
              </div>
            </template>
          </div>
        </div>

        <!-- 相关推荐区 -->
        <div class="recommendations-section">
          <h2>相关推荐</h2>
          <div class="recommendations-grid">
            <el-card
                v-for="item in recommendedBooks"
                :key="item.bookId"
                class="recommendation-card"
                shadow="hover"
                @click="handleBookClick(item)"
            >
              <div class="book-cover">
                <img :src="item.coverImage" :alt="item.title">
              </div>
              <div class="book-info">
                <h3 class="book-title">{{ item.title }}</h3>
                <p class="book-author">{{ item.author }}</p>
                <p class="book-desc">{{ item.description }}</p>
              </div>
            </el-card>
          </div>
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.book-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 20px;
  transition: all 0.3s ease;
  background-color: #f2f3f5;
  border: none;
  color: #606266;
}

.back-button:hover {
  background-color: #e4e7ed;
  color: #409eff;
}

.back-button .el-icon {
  font-size: 16px;
}

.book-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 40px;
  margin-bottom: 40px;
}

.book-image {
  position: relative;
}

.book-image img {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.borrow-button {
  width: 100%;
  margin-top: 0;
}

.book-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.book-title {
  font-size: 36px;
  font-weight: 800;
  color: #1a1a1a;
  margin: 0 0 28px;
  line-height: 1.2;
  letter-spacing: 0.5px;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.05);
}

.comments-section {
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #eee;
}

.rating-summary {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.average-rating-label {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.rating-count {
  color: #666;
  font-size: 14px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.comment-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #2c3e50;
}

.comment-date {
  color: #999;
  font-size: 13px;
}

.comment-content {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.comment-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.recommendations-section {
  margin-top: 40px;
  padding-top: 40px;
  border-top: 1px solid #eee;
}

.recommendations-section h2 {
  margin-bottom: 24px;
  font-size: 20px;
  color: #2c3e50;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 24px;
}

.recommendation-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.recommendation-card:hover {
  transform: translateY(-5px);
}

.book-cover {
  width: 100%;
  height: 280px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 12px;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.recommendation-card:hover .book-cover img {
  transform: scale(1.05);
}

.book-info {
  padding: 0 8px;
}

.book-info .book-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-info .book-author {
  font-size: 14px;
  color: #666;
  margin: 0 0 8px;
}

.book-info .book-desc {
  font-size: 13px;
  color: #999;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

/* 修改热度评分的样式 */
.popularity-score {
  display: flex;
  align-items: center;
  gap: 8px;
}

.score-number {
  color: #333;
  font-size: 14px;
  min-width: 30px;
}

.book-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}

.borrow-button,
.favorite-button {
  flex: 1;
  height: 40px;
  font-size: 14px;
}

.favorite-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.favorite-button .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.author-name.clickable {
  color: #333;
  cursor: pointer;
  transition: color 0.3s ease;
}

.author-name.clickable:hover {
  color: #ffd04b;
}
</style> 